import { Card, Checkbox, Form, Input, Button, message } from 'antd'
import { useDispatch } from 'react-redux'
import logo from '../../assets/logo.png'
import styles from './index.module.scss'
import { userLogin } from '@/store/actions/login'
import { useState } from 'react'
import { useHistory } from 'react-router-dom'
const Login = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const [isLoading, setIsLoading] = useState(false)
  const onFinish = async (values) => {
    // 只有表单校验通过，才会到这里
    console.log('表单数据', values)
    try {
      setIsLoading(true)
      // 发请求做登录
      // dispatch(异步的)
      await dispatch(userLogin(values))
      // 1. 提示成功
      message.success('登录成功', 1.5, () => {
        console.log('页面跳转')
        // 2. 页面跳转
        let pathName = '/home'
        if(history.location.state){
          pathName = history.location.state.from || '/home'
        }
        // history.push('/home')
        history.replace(pathName)
      })
    } catch (err) {
      // console.dir(err)
      const msg = err.response.data.message || '登录失败'
      message.error(msg)
    } finally {
      setIsLoading(false)
    }
  }
  return (
    <div className={styles.root}>
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form
          initialValues={{mobile: '13911111111', code: '246810', isAgree: true}}
          onFinish={onFinish}
          validateTrigger={['onBlur']}
          autoComplete="off" size="large">
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: /^1\d{10}$/, message: '手机号格式不对'}
            ]}
            >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item
            name="code"
            rules={[
              { required: true, message: '验证码不能为空' },
              { pattern: /^\d{6}$/, message: '验证码格式不对'}
            ]}>
            <Input placeholder="请输入验证码" />
          </Form.Item>

          <Form.Item
            name="isAgree"
            valuePropName="checked"
            rules={
              [ 
                { 
                  validator (rule, value) {
                    if(value) {
                      // 返回一个成功状态的promise
                      return Promise.resolve()
                    } else {
                      return Promise.reject(new Error('你必须先同意，才能登录'))
                    }
                  }
                } 
              ]
            }
          >
            <Checkbox>我已阅读并同意[隐私条款]和[用户协议]</Checkbox>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit" block loading={isLoading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login
